<template>
  <view>
    <view class="bg">
      <view class="score-time">
        <p class="score">
          历史最高分：<span>{{ myCache('rankScore') }}</span>
        </p>
      </view>
      <view class="score-time">
        <p class="score">
          积分：<span>{{ currentScore }}</span>
        </p>
        <p class="score">
          倒计时：<span>{{ countDown }}s</span>
        </p>
      </view>
      <view class="music-box"> </view>
      <!-- <view v-if="!countDown" class="btns">
				<view @click="listenMore" class="btn" plain>再听一遍</view>
			</view> -->
      <view class="answer-box">
        <view
          @click="handleSelect(item)"
          v-for="(item, index) in currentQuestion.answers"
          :key="index"
          class="answer"
          :style="answerStyle(item)"
        >
          <p :style="textStyle(item)">
            {{ item }}
          </p>
          <template v-if="currentAnswer || isTimeOut">
            <u-icon
              v-if="item === questionData[currentIndex].trueAnswer"
              name="checkmark"
              color="#1FB55B"
              size="28"
            />
            <u-icon v-else name="close" color="#FF5050" size="28" />
          </template>
        </view>
      </view>
      <audio ref="audio" :src="currentQuestion.musicUrl" />
      <view
        v-if="
          (currentAnswer && currentIndex !== questionData.length - 1) ||
          (isTimeOut && currentIndex !== questionData.length - 1)
        "
        @click="handleNext"
        class="btn"
        plain
      >
        下一题
      </view>
      <view v-if="currentIndex === questionData.length - 1" @click="handleFinish" class="btn" plain>
        完成
      </view>
    </view>
    <uni-popup ref="popup-box">
      <view class="popup-box">
        <span>{{ isTrue ? '答对啦！' : '答错啦！' }}</span>
      </view>
    </uni-popup>
    <uni-popup ref="popup-timeout">
      <view class="popup-box">
        <span>超时啦！</span>
      </view>
    </uni-popup>
    <uni-popup ref="popup-start">
      <view class="popup-box">
        <view>
          <b>Are you ok?</b>
        </view>
        <view
          @click="autoPlay"
          style="
            background: #3b97ff;
            border-radius: 33rpx;
            padding: 10rpx 20rpx;
            text-align: center;
            font-size: 28rpx;
            color: #fff;
          "
        >
          立即开始
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="popup-end">
      <view class="popup-box">
        <view>
          <b>游戏结束</b>
        </view>
        <p style="margin-top: 0; text-align: center">
          <span>本次得分{{ currentScore }}</span>
          <span v-if="isRecord">,恭喜您打破记录拉！</span>
        </p>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { questionData } from './static/data'
import { myCache } from '@/utils.js'
export default {
  data() {
    return {
      myCache,
      timer: null, // 定时器
      isTimeOut: false, // 是否超时
      questionData,
      currentIndex: 0, // 当前题目索引
      currentScore: 0, // 积分
      currentQuestion: null, // 当前题目
      countDown: 20, // 倒计时
      currentAnswer: null, // 用户选择的答案
      audio: null, // 音频
      isRecord: false // 是否是最高记录
    }
  },
  computed: {
    isTrue() {
      return (
        this.currentAnswer && this.currentAnswer === this.questionData[this.currentIndex].trueAnswer
      )
    }
  },
  async onReady() {
    this.audio = document.getElementsByTagName('audio')
  },
  onLoad() {
    this.audio = null
    this.currentQuestion = this.questionData[this.currentIndex]
    this.$nextTick(() => {
      this.$refs['popup-start'].open()
      this.$refs['popup-start'].disableMask()
    })
  },
  onBackPress() {
    this.reset()
  },
  methods: {
    answerStyle(item) {
      if (!this.currentAnswer || this.currentAnswer !== item) return ''
      if (
        this.currentAnswer === this.questionData[this.currentIndex].trueAnswer &&
        this.currentAnswer === item
      )
        return 'backgroundColor:#1FB55B'
      return 'backgroundColor:#FF5050'
    },
    textStyle(item) {
      if (
        this.currentAnswer === this.questionData[this.currentIndex].trueAnswer &&
        this.currentAnswer === item
      )
        return 'color:#FFF'
      return ''
    },
    autoPlay(type) {
      if (type === 'next') {
        this.audio[0].autoplay = true
        this.audio[0].src = this.currentQuestion.musicUrl
        const play = () => {
          this.audio[0].play().catch(err => {
            console.log(JSON.stringify(err))
            play()
          })
        }
      } else {
        this.$refs['popup-start'].close()
        this.audio[0].play()
      }

      this.timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--
        } else {
          clearInterval(this.timer)
          this.isTimeOut = true
          if (!this.currentAnswer) {
            this.$refs['popup-timeout'].open()
          }
        }
      }, 1000)
    },
    listenMore() {
      this.countDown = 20
    },
    handleSelect(answer) {
      if (this.currentAnswer || this.isTimeOut) return
      clearInterval(this.timer)
      this.currentAnswer = answer
      if (answer === this.currentQuestion.trueAnswer) {
        this.currentScore += 20
      }
      this.$refs['popup-box'].open()
      this.$refs['popup-box'].disableMask()
      setTimeout(() => {
        this.$refs['popup-box'].close()
        if (this.currentIndex === this.questionData.length - 1) {
          this.$refs['popup-end'].open()
          if (!myCache('rankScore') || myCache('rankScore') < this.currentScore) {
            myCache('rankScore', this.currentScore)
            this.isRecord = true
          }
        }
      }, 1500)
    },
    handleNext() {
      this.currentAnswer = null
      this.isTimeOut = false
      this.currentIndex++
      this.currentQuestion = this.questionData[this.currentIndex]
      this.countDown = 20
      this.autoPlay('next')
    },
    handleFinish() {
      this.reset()
      uni.navigateBack()
    },
    reset() {
      this.currentAnswer = null
      this.isTimeOut = false
      this.audio = null
    }
  }
}
</script>

<style lang="scss">
.bg {
  width: 100vw;
  min-height: 100vh;
  background-image: url('../../static/bg.jpg');
  background-size: 100% 100%;
  padding: 30rpx;
  box-sizing: border-box;

  .score-time {
    margin-top: 30rpx;
    display: flex;
    justify-content: space-between;

    .score {
      display: flex;
      color: #ffffff;
      font-size: 35rpx;
      height: 80rpx;
      line-height: 80rpx;

      span {
        color: #ff5050;
        font-weight: bold;
        font-size: 45rpx;
        margin: auto 0;
      }
    }
  }

  .btn {
    width: 200rpx;
    height: 88rpx;
    margin: 0 auto;
    background: #ff7f29;
    border-radius: 44rpx;
    font-weight: bold;
    font-size: 32rpx;
    color: #ffffff;
    line-height: 88rpx;
    text-align: center;
  }

  .btns {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
  }

  .answer-box {
    display: flex;
    flex-direction: column;
    margin-top: 30rpx;

    .answer {
      display: flex;
      margin: 0 auto;
      margin-bottom: 30rpx;
      width: 400rpx;
      height: 72rpx;
      background: #f0f0f0;
      border-radius: 36rpx;

      p {
        margin: 0 auto;
        font-weight: 400;
        font-size: 28rpx;
        color: #949494;
        text-align: center;
        line-height: 72rpx;
      }
    }
  }

  .music-box {
    width: 500rpx;
    height: 500rpx;
    border-radius: 50%;
    margin: 0 auto;
    margin-top: 50rpx;
    background-image: url('../../static/music.gif');
    background-size: 100% 100%;
  }
}

.popup-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 250rpx;
  height: 150rpx;
  background: linear-gradient(0deg, #ffffff, #dbf2ff);
  border-radius: 20rpx;
  padding: 50rpx;

  span {
    margin: auto;
    text-align: center;
    font-weight: bold;
    font-size: 32rpx;
    color: #3b97ff;
    text-align: center;
  }

  b {
    position: relative;
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
    font-weight: bold;
    font-size: 32rpx;
    color: #3b97ff;
    text-align: center;
  }

  b::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 32rpx;
    height: 4rpx;
    background: #3b97ff;
    border-radius: 2rpx;
  }

  p {
    margin-top: 50rpx;
    font-weight: 400;
    font-size: 24rpx;
    color: #383838;
  }
}
</style>
